package com.haitaoit.chengquan.module.home.activity.maintenance;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.model.SeachDemandModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.activity.ShowPictureActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.ImageCycleView;
import com.haitaoit.chengquan.view.Img;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SeachDemandActivity extends BaseActivity {
    @ViewInject(R.id.topImgOnlyOne)
    ImageView      topImgOnlyOne;
    @ViewInject(R.id.topImg)
    ImageCycleView topImg;
    @ViewInject(R.id.demand_title)
    TextView       demand_title;
    @ViewInject(R.id.reference_price)
    TextView       reference_price;
    @ViewInject(R.id.addtime)
    TextView       addtime;
    @ViewInject(R.id.type)
    TextView       type;
    @ViewInject(R.id.contact)
    TextView       contact;
    @ViewInject(R.id.contact_phone)
    TextView       contact_phone;
    @ViewInject(R.id.demand_site)
    TextView       demand_site;
    @ViewInject(R.id.cs_list)
    TextView       cs_list;
    @ViewInject(R.id.describe)
    TextView       describe;
    @ViewInject(R.id.cs_list2)
    TextView       cs_list2;
    @ViewInject(R.id.demand_time)
    TextView       demand_time;
    @ViewInject(R.id.part_offer)
    TextView       part_offer;
    private String      id;
    private Timer timer = new Timer();
    private long  time  = 0;
    private Dialog           dlg;
    private SeachDemandModel model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_seach_demand);
        ViewUtils.inject(this);
        setLeftShow(1, R.mipmap.left);
        setTitle_V("需求详情");
        backLeft_V();


        DisplayMetrics metrics = getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp1 = topImg.getLayoutParams();
        lp1.height = (metrics.widthPixels / 2);
        topImg.setLayoutParams(lp1);
        topImgOnlyOne.setLayoutParams(lp1);
        id = getIntent().getStringExtra("id");
        httpGetdemand_model();

        if (TextUtils.equals("1", PreferenceUtils.getPrefString("account_type", ""))) {
            part_offer.setVisibility(View.GONE);
        }
        String see = PreferenceUtils.getPrefString("see", "");

        System.out.println(see);
        System.out.println(see);
        System.out.println(see);

        if (TextUtils.equals(see,2+"")||TextUtils.equals(see,6+"")||TextUtils.equals(see,7+"")){
            part_offer.setVisibility(View.GONE);
            PreferenceUtils.setPrefString("see","");
        }

    }

    @OnClick({R.id.contact_phone, R.id.demand_site, R.id.part_offer})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.contact_phone:
                startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + model.getContact_phone())));
                break;
            case R.id.demand_site:
                intent.setClass(this, MapGpsActivity.class);
                intent.putExtra("longitude", model.getLongitude());
                intent.putExtra("latitude", model.getLatitude());
                startActivity(intent);
                break;
            case R.id.part_offer:
                if (time > 0) {
                    if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                        intent.setClass(this, LoginActivity.class);
                        intent.putExtra("tag", "0");
                        startActivity(intent);
                    } else if (PreferenceUtils.getPrefString("account_type", "").equals("2") ||
                            PreferenceUtils.getPrefString("account_type", "").equals("3")) {
                        Dialog dlg = ShowPriceDialog(SeachDemandActivity.this);
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();

                        DisplayMetrics metric = new DisplayMetrics();
                        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                        int width = metric.widthPixels; // 屏幕宽度（像素）
                        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                        params.width = width;
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        dlg.getWindow().setAttributes(params);
                    } else {
                        ToastUtils.showToast("该账号不是服务商！");
                    }
                } else {
                    ToastUtils.showToast("参与报价时间已过！");
                }
                //                iniPopupWindow();
                //                myPopWindow.showAtLocation(SeachDemandActivity.this.findViewById(R.id.activity_seach_demand),
                //                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
        }
        super.onClick(v);
    }

    private void httpGetdemand_model() {
        String user_id = PreferenceUtils.getPrefString("user_id", "");
        if ("".equals(user_id))
            user_id = "0";
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        list.add(new NameValuePairSign("user_id", user_id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("user_id", user_id);
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, true, Constant.Getdemand_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            hideProgree();
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, SeachDemandModel.class);

                            if (model.getImg_list() != null && model.getImg_list().size() > 0) {
                                if (model.getImg_list().size() == 1) {
                                    Glide.with(SeachDemandActivity.this).load(model.getImg_list().get(0).getImg_url()).into(topImgOnlyOne);
                                    topImgOnlyOne.setVisibility(View.VISIBLE);
                                    topImg.setVisibility(View.GONE);
                                } else {
                                    topImg.setImageResources(model.getImg_list(), listener);
                                    topImgOnlyOne.setVisibility(View.GONE);
                                    topImg.setVisibility(View.VISIBLE);
                                }
                            }
                            demand_title.setText(model.getTitle());
                            reference_price.setText("¥ " + model.getReference_price() + "元");
                            addtime.setText("发布：" + model.getAddtime());
                            type.setText("分类：" + model.getType());
                            contact.setText("发布者：" + model.getContact());
                            contact_phone.setText("联系方式：" + model.getContact_phone());
                            demand_site.setText("地址：" + model.getDemand_site());
                            String sc = "";
                            String sc2 = "";
                            for (int i = 0; i < model.getCs_list().size(); i++) {
                                if ((i + 1) % 2 == 0) {
                                    sc2 = sc2 + "      " + model.getCs_list().get(i).getContent() + "\n";
                                } else {
                                    sc = sc + model.getCs_list().get(i).getContent() + "\n";
                                }
                            }
                            sc = sc.substring(0, sc.length() - 1);
                            cs_list.setText(sc);
                            cs_list2.setText(sc2);
                            describe.setText(model.getDescribe());
                            // 1不显示报价2显示
                            if (model.getIs_offer().equals("1")) {
                                part_offer.setVisibility(View.GONE);
                            }

                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date d1 = dateFormat.parse(model.getOffer_end_time());
                            Date d2 = dateFormat.parse(dateFormat.format(new java.util.Date()));
                            if (d1.getTime() < d2.getTime()) {
                                time = 0;
                            } else {
                                time = (d1.getTime() - d2.getTime());// 这样得到的差值是微秒级别
                                timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        if (time > 0) {
                                            time--;
                                        }
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                setDate();
                                            }
                                        });
                                    }
                                }, 0, 1);
                            }
                            return;
                    }
                    hideProgree();
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                } catch (Exception e) {
                    e.printStackTrace();
                    hideProgree();

                }
            }


            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }
        });
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    // 提交报价信息
    private void httpGetdemand_offer(String qq, String email, String offer_money, String contact_information, String remarks) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("demand_id", id));
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("offer_money", offer_money));
        list.add(new NameValuePairSign("contact_information", contact_information));
        list.add(new NameValuePairSign("contact_email", email));
        list.add(new NameValuePairSign("contact_qq", qq));
        list.add(new NameValuePairSign("remarks", remarks));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("demand_id", id);
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("offer_money", offer_money);
        params.addQueryStringParameter("contact_information", contact_information);
        params.addQueryStringParameter("contact_email", email);
        params.addQueryStringParameter("contact_qq", qq);
        params.addQueryStringParameter("remarks", remarks);
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, false, Constant.Getdemand_offer, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            dlg.dismiss();
                            httpGetdemand_model();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    // 报价
    public Dialog ShowPriceDialog(Context context) {
        dlg = new Dialog(context, R.style.PushUpInDialogThem);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.send_offer_info, null);
        final EditText offer_money = (EditText) layout.findViewById(R.id.offer_money);
        final EditText offer_phone = (EditText) layout.findViewById(R.id.offer_phone);
        final EditText remarks = (EditText) layout.findViewById(R.id.remarks);
        //邮箱号码
        final EditText offer_email = (EditText) layout.findViewById(R.id.offer_email);
        final EditText offer_qq = (EditText) layout.findViewById(R.id.offer_qq);


        //提交报价
        layout.findViewById(R.id.send_price).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (offer_money.getText().toString().equals("")) {
                    ToastUtils.showToast("请填写报价！");
                    return;
                }

                String phone = offer_phone.getText().toString().trim();
                String email = offer_email.getText().toString().trim();
                String qq = offer_qq.getText().toString().trim();
                boolean bPhone = Utils.isMobileNum(phone);
                boolean bEmail = Utils.isEmail(email);
                boolean bQq = isNumeric(qq);
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showToast("手机号为必填项");
                    return;
                }
                if (!bPhone) {
                    ToastUtils.showToast("手机号不正确");
                    return;
                }
                if (!TextUtils.isEmpty(email) && !bEmail) {
                    ToastUtils.showToast("邮箱不正确,请核对");
                    return;
                }
                if (!TextUtils.isEmpty(qq) && !bQq) {
                    ToastUtils.showToast("QQ号码不正确,请核对");
                    return;
                }


                //                else if (!Utils.isMobileNum(offer_phone.getText().toString())&&!Utils.isEmail(offer_phone.getText().toString())&&!isNumeric(offer_phone.getText().toString())) {
                //                    ToastUtils.showToast("联系方式格式有误请重新输入！");
                //                } else {

                httpGetdemand_offer(qq,email,offer_money.getText().toString(),
                        offer_phone.getText().toString(), remarks.getText().toString());
                //                }
            }
        });

        layout.findViewById(R.id.dismiss_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });
        layout.findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlg.dismiss();
            }
        });

        Window w = dlg.getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        dlg.onWindowAttributesChanged(lp);
        dlg.setContentView(layout);
        dlg.setCancelable(false);
        return dlg;
    }

    public void setDate() {
        int days = (int) (time / (24 * 60 * 60 * 1000));
        int hourNum = (int) (time / (60 * 60 * 1000) - days * 24);
        int minuteNum = (int) ((time / (60 * 1000)) - days * 24 * 60 - hourNum * 60);
        int secondNum = (int) (time / 1000 - days * 24 * 60 * 60 - hourNum * 60 * 60 - minuteNum * 60);
        demand_time.setText("剩余时间：" + days + "天" + formatDate(hourNum) +
                "时" + formatDate(minuteNum) + "分" + formatDate(secondNum) + "秒");
        if (time == 0) {
            timer.cancel();
        }
    }

    public String formatDate(int time) {
        if (time > 9) {
            return time + "";
        } else if (time == 0) {
            return "00";
        } else if (time < 0) {
            return "00";
        } else {
            return "0" + time;
        }
    }

    /**
     * 轮播图点击事件
     */
    ImageCycleView.ImageCycleViewListener listener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void displayImage(Img img, ImageView imageView) {
            ImageLoader.getInstance().displayImage(img.getImg_url(), imageView);
        }

        @Override
        public void onImageClick(int position, View imageView) {

            Intent intent = new Intent();
            intent.setClass(SeachDemandActivity.this, ShowPictureActivity.class);
            intent.putExtra("image_uri", model.getImg_list().get(position).getImg_url());
            startActivity(intent);
        }

        @Override
        public void onImageChange(int position, List<Img> imageUrlList) {
        }
    };

    //    private void iniPopupWindow() {
    //        LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    //        View layout = inflater.inflate(R.layout.send_offer_info, null);//POP的布局
    //
    //        layout.findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                myPopWindow.dismiss();
    //            }
    //        });
    //        layout.findViewById(R.id.dismiss_view).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                myPopWindow.dismiss();
    //            }
    //        });
    //
    //        layout.findViewById(R.id.send_price).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //            }
    //        });
    //        myPopWindow = new PopupWindow(layout);
    //        myPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
    //        // 控制popupwindow 的宽度和高度
    //        myPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
    //        myPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    //        // 控制popupwindow 点击屏幕其他地方消失
    //        myPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
    //        myPopWindow.setOutsideTouchable(true); // 触摸popupwindow 外部,popupwindow消失,这个要求你的 popupwindow要有背景图片才可以成功
    //    }

}
